﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace Dracham.Classes
{
    public class Tile
    {
        public Boolean IsSolid { get; set; }
        public Position Position { get; set; }
        public List<Event> Events { get; set; }

        public Tile() 
        {
            this.Events = new List<Event>();
        }

        public Tile(XmlNode objectNode, Zone zone)
        {
            this.Events = new List<Event>();
            this.Position = new Position(
                Convert.ToInt32(objectNode.Attributes["X"].Value),
                Convert.ToInt32(objectNode.Attributes["Y"].Value),
                zone.ZoneId);

            var res = from XmlAttribute x in objectNode.Attributes where x.Name == "Solid" select x.Value;
            if (res.Count<String>() == 1)
                this.IsSolid = Convert.ToBoolean(res.FirstOrDefault<String>());

            if (objectNode.HasChildNodes)
            {
                XmlNodeList childNodes = objectNode.ChildNodes;

                var result = from XmlNode x in childNodes where x.Name == "Spawn" select x;
                SpawnTimer s = SpawnTimer.FromXmlNode(result.FirstOrDefault<XmlNode>(), this.Position);
                if (s != null) s.Run();

                result = from XmlNode x in childNodes where x.Name == "OnEnter" select x;
                OnEnter oe = OnEnter.FromXmlNode(result.FirstOrDefault<XmlNode>());
                if (oe != null) this.Events.Add(oe);
            }
        }

        public void Step(Character c)
        {
            foreach (OnEnter e in this.Events)
            {
                Teleport t = e.GetAction<Teleport>(typeof(Teleport));
                if (t != null) c.Move(t.Destination);
            }
        }

        public Object[] ObjectsOnTile
        {
            get
            {
                return this.Position.Zone.Objects.Where(o => o.Position == this.Position).ToArray();
            }
        }
    }
}
